/**
 * Copyright (c) 2020 lizebang
 *
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

package jiri

import (
	"flag"
	"os"
	"path/filepath"

	"go.fuchsia.dev/jiri"
	"go.fuchsia.dev/jiri/cmdline"

	"gitee.com/banggua/ggtsync/config"
	"gitee.com/banggua/ggtsync/logger"
)

func (jc *jiriClient) jiriInit(project *config.Project) (func(), error) {
	jiriRootTempDir := filepath.Join(project.To, project.Name+".TempDir")
	err := os.MkdirAll(jiriRootTempDir, 0755)
	if err != nil {
		logger.Errorf("%v %v", project, err)
		return nil, err
	}

	jiriRootMetaDir := filepath.Join(jiriRootTempDir, jiri.RootMetaDir)
	if _, err := os.Stat(jiriRootMetaDir); err != nil {
		if !os.IsNotExist(err) {
			logger.Errorf("%v %v", project, err)
			return nil, err
		}
		if err := os.Mkdir(jiriRootMetaDir, 0755); err != nil {
			logger.Errorf("%v %v", project, err)
			return nil, err
		}
	}

	config := &jiri.Config{}
	configPath := filepath.Join(jiriRootMetaDir, jiri.ConfigFile)
	if _, err := os.Stat(configPath); err == nil {
		config, err = jiri.ConfigFromFile(configPath)
		if err != nil {
			logger.Errorf("%v %v", project, err)
			return nil, err
		}
	} else if !os.IsNotExist(err) {
		logger.Errorf("%v %v", project, err)
		return nil, err
	}

	if err := config.Write(configPath); err != nil {
		logger.Errorf("%v %v", project, err)
		return nil, err
	}
	// TODO(phosek): also create an empty manifest

	if err := flag.Set("root", jiriRootTempDir); err != nil {
		logger.Errorf("%v %v", project, err)
		return nil, err
	}

	jirix, err := jiri.NewX(cmdline.EnvFromOS())
	if err != nil {
		logger.Errorf("%v %v", project, err)
		return nil, err
	}

	jc.locker.Lock()
	defer jc.locker.Unlock()
	jc.Xs[project.Name] = jirix
	return func() {
		os.RemoveAll(jiriRootTempDir)
	}, nil
}
